package com.cindata.api

import grails.converters.JSON
import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer

//import groovyx.net.http.HTTPBuilder
import groovyx.net.http.OkHttpBuilder
import net.sf.json.JSONObject
import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

class DeveloperApiService implements InitializingBean
{

    static scope = "singleton"
    OkHttpBuilder http

    @Value('${developerApi.address}')
    String apiAddress
    @Value('${developerApi.evaluate}')
    String evaluateApi
    @Value('${developerApi.orginInfo}')
    String orginInfoApi
    @Value('${developerApi.contactInfo}')
    String contactInfoApi
    /**
     * 开发商信息
     * @param companyId
     */
    def getCompanyInfo(String companyName)
    {
        def result
        try
        {
            result = get(evaluateApi, [company: companyName])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 开发商和负面信息原始数据
     * @param companyId
     */
    def getOrginInfo(String companyName)
    {
        def result
        try
        {
            result = get(orginInfoApi, [company: companyName])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                      data: [:],
                      message: ex.getMessage()]
        }
        return result
    }

    /**
     * 借款人信息查询
     * @param companyId
     */
    def getContactInfo(String idNumber,String fullName)
    {
        def result
        try
        {
            result = get(contactInfoApi, [idNumber: idNumber,fullName:fullName])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                      data: [:],
                      message: ex.getMessage()]
        }
        return result
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            request.uri = apiAddress
            // request.headers["Cache-Control"] = ["no-cache"]
            client.clientCustomizer { OkHttpClient.Builder builder ->
                builder.connectTimeout(10, TimeUnit.SECONDS)
                builder.readTimeout(20, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path},key：${request.uri.query}")
                log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def get(String url, Map data)
    {
        try
        {
            http.get {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                data?.each { key, value -> request.uri.query[key] = value
                }
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    // println "result:"+json.toString()
                    return json
                }
                response.failure { FromServer resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

//    最原始的get请求
    def getOrgin(String url)
    {
        def result = "";
        BufferedReader inn ;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "application/json;");
            connection.connect();
             inn = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = inn.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (inn != null) {
                    inn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return new JSONObject().fromObject(result);
    }


    //    最原始的get请求
    def postOrgin(String url,String param)
    {
        java.io.PrintWriter out = null;
        java.io.BufferedReader inn = null;
        java.lang.String result = "";
        try {
            java.net.URL realUrl = new java.net.URL(url);
            // 打开和URL之间的连接
            java.net.URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new java.io.PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            inn = new java.io.BufferedReader(new java.io.InputStreamReader(
                    conn.getInputStream(), "utf-8"));
            String line;
            while ((line = inn.readLine()) != null) {
                result += line;

            }
        } catch (java.lang.Exception e) {
            println "发送 POST 请求出现异常！" + e
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inn != null) {
                    inn.close();
                }
            } catch (java.io.IOException ex) {
                ex.printStackTrace();
            }
        }
        return new net.sf.json.JSONObject().fromObject(result)
    }
}
